﻿using System;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using BaseWordStat;
using NetService.Parser;

namespace NetService
{
    public static class PageService
    {
        internal static string GetPage(string urlAddress)
        {
            var request = (HttpWebRequest)WebRequest.Create(urlAddress);

            // Set some reasonable limits on resources used by this request
            request.MaximumAutomaticRedirections = 4;
            request.MaximumResponseHeadersLength = 4;
            // Set credentials to use for this request.
            request.Credentials = CredentialCache.DefaultCredentials;
            var response = (HttpWebResponse)request.GetResponse();

            // Get the stream associated with the response.
            var receiveStream = response.GetResponseStream();

            // Pipes the stream to a higher level stream reader with the required encoding format. 
            var readStream = new StreamReader(receiveStream, Encoding.UTF8);

            return readStream.ReadToEnd();
        }

        public static Article GetArticleData(string articleUrl)
        {
            var text = GetPage(articleUrl);

            var article = new Article();

            article.Date = DateTime.Now;

            article.Author = HtmlParser.GetAuthor(text);

            if (string.IsNullOrEmpty(article.Author))
                return null;

            article.Date = HtmlParser.GetDate(text);

            var url = HtmlParser.GetUrl(text);

            if (string.IsNullOrEmpty(url))
                return null;

            article.Url = articleUrl;

            article.Title = HtmlParser.GetTitle(text);

            if (string.IsNullOrEmpty(article.Title))
                return null;

            article.Text = HtmlParser.GetArticle(text).Trim();

            if (string.IsNullOrEmpty(article.Text))
                return null;

            article.Words = HtmlParser.GetWords(article.Text);

            if (article.Words.Count == 0)
                return null;

            article.Source = "newsweek";

            return article;
        }
    }
}
